-module(xbt_test).

-export([start/3,utest/2,close/1]).

-include("xbt.hrl").

start(Host,User,Pass)  ->
    {ok,Socket} = gen_tcp:connect(Host, 51206, [binary,{packet,2},{active,false}]),
    TimeStamp = get_timestamp(),
    AuthCode = get_authcode(User,Pass,TimeStamp),
    User1 = pad_user(User),
    Sequence = 1,
    ok = xbt_tcp_proto:send_packet(Socket,?TABLE_BIND,Sequence,{User1,AuthCode,?VERSION,TimeStamp}),
    Pack = xbt_tcp_proto:get_packet(Socket),
    {ok,{?TABLE_BIND_RESP,Sequence,{?CODE_OK,_Version}}} = xbt_tcp_proto:parse_packet(Pack),
    Socket.

utest(set,{Socket,Name,Value})  ->
    Sequence = 10,
    Data = {list_to_binary(Name),list_to_binary(Value)},
    ok = xbt_tcp_proto:send_packet(Socket,?TABLE_SET,Sequence,Data),
    Pack = xbt_tcp_proto:get_packet(Socket),
    {ok,{?TABLE_SET_RESP,Sequence,{?CODE_OK}}} = xbt_tcp_proto:parse_packet(Pack);

utest(get,{Socket,Name})  ->
    Sequence = 20,
    N1 = list_to_binary(Name),
    ok = xbt_tcp_proto:send_packet(Socket,?TABLE_GET,Sequence,{N1}),
    Pack = xbt_tcp_proto:get_packet(Socket),
    xbt_tcp_proto:parse_packet(Pack);

utest(append,{Socket,Name,Value})  ->
    Sequence = 30,
    N1 = list_to_binary(Name),
    V1 = list_to_binary(Value),
    Data = {N1,V1},
    ok = xbt_tcp_proto:send_packet(Socket,?TABLE_APPEND,Sequence,Data),
    Pack = xbt_tcp_proto:get_packet(Socket),
    {ok,{?TABLE_APPEND_RESP,Sequence,{?CODE_OK}}} = xbt_tcp_proto:parse_packet(Pack);

utest(active,{Socket})  ->
    Sequence = 40,
    ok = xbt_tcp_proto:send_packet(Socket,?TABLE_ACTIVE_TEST,Sequence,{}),
    Pack = xbt_tcp_proto:get_packet(Socket),
    {ok,{?TABLE_ACTIVE_TEST_RESP,Sequence,[]}} = xbt_tcp_proto:parse_packet(Pack);

utest(delete,{Socket,Name})  ->
    Sequence = 50,
    N1 = list_to_binary(Name),
    ok = xbt_tcp_proto:send_packet(Socket,?TABLE_DEL,Sequence,{N1}),
    Pack = xbt_tcp_proto:get_packet(Socket),
    {ok,{?TABLE_DEL_RESP,Sequence,{?CODE_OK,N1}}} = xbt_tcp_proto:parse_packet(Pack).

close(Socket) ->
    gen_tcp:close(Socket).

get_timestamp()  ->
    {{_YY,MM,DD},{HH,MI,SS}} = calendar:local_time(),
    TimeList = io_lib:format("~2.2.0w~2.2.0w~2.2.0w~2.2.0w~2.2.0w",[MM,DD,HH,MI,SS]),
    list_to_binary(TimeList).

get_authcode(User,Pass,TimeStamp)   ->
    Md5in = list_to_binary([User,Pass,TimeStamp]),
    crypto:start(),
    Md5out = crypto:md5(Md5in),
    crypto:stop(),
    Md5out.

pad_user(User)  ->
    Pad = "\000\000\000\000\000",
    U1 = string:concat(User,Pad),
    list_to_binary(string:substr(U1,1,6)).

